package com.governtalk.backend.repository;

import com.governtalk.backend.entity.GroupMember;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface GroupMemberRepository extends JpaRepository<GroupMember, Long> {
    
    // 查找用户加入的所有小组
    List<GroupMember> findByUserIdAndStatus(Long userId, GroupMember.GroupMemberStatus status);
    
    // 查找小组的所有成员
    List<GroupMember> findByGroupIdAndStatus(Long groupId, GroupMember.GroupMemberStatus status);
    
    // 检查用户是否已加入小组
    boolean existsByGroupIdAndUserId(Long groupId, Long userId);
    
    // 查找用户在特定小组的成员信息
    Optional<GroupMember> findByGroupIdAndUserId(Long groupId, Long userId);
    
    // 统计小组成员数量
    long countByGroupIdAndStatus(Long groupId, GroupMember.GroupMemberStatus status);
    
    // 查找小组管理员
    @Query("SELECT gm FROM GroupMember gm WHERE gm.group.id = :groupId AND gm.role = 'ADMIN' AND gm.status = 'ACTIVE'")
    List<GroupMember> findGroupAdmins(@Param("groupId") Long groupId);
    
    // 查找小组版主
    @Query("SELECT gm FROM GroupMember gm WHERE gm.group.id = :groupId AND gm.role = 'MODERATOR' AND gm.status = 'ACTIVE'")
    List<GroupMember> findGroupModerators(@Param("groupId") Long groupId);
    
    // 检查用户是否是小组管理员
    boolean existsByGroupIdAndUserIdAndRoleAndStatus(Long groupId, Long userId, GroupMember.GroupRole role, GroupMember.GroupMemberStatus status);
}

